/*
 * @Description: 大前端学习
 * @Version: H5
 * @Author: Ajax
 * @Date: 2020-05-11 10:00:46
 * @LastEditors: Ajax
 * @LastEditTime: 2020-05-11 14:00:07
 */

; (function () {
    let that = null     // 改变 this 指向
    function Game(map) {
        this.food = new Food()
        this.snake = new Snake()
        this.map = map
        // 出作用域
        that = this
    }

    // 开始游戏
    Game.prototype.start = function () {
        // 渲染
        this.food.render(this.map)
        this.snake.render(this.map)

        // 测试 move方法
        // this.snake.move()
        // this.snake.render(this.map)

        // 游戏逻辑处理
        // 1 蛇自动移动
        autoMove()
        // 2 键盘控制蛇移动的方向
        controlSnake()
        // 3 蛇吃食物
    }

    // 控制蛇
    function controlSnake() {
        document.addEventListener('keydown', (e) => {
            switch (e.keyCode) {
                case 37:
                    that.snake.direction = 'left'
                    break
                case 38:
                    that.snake.direction = 'top'
                    break
                case 39:
                    that.snake.direction = 'right'
                    break
                case 40:
                    that.snake.direction = 'bottom'
                    break
            }
        }, false)
    }

    // 蛇自动移动
    function autoMove() {
        let time = setInterval(() => {   // this 指向 window
            // 让蛇走一格
            that.snake.move(that.food, that.map)
            that.snake.render(that.map)
            // 2 限定边界
            // 获取蛇的坐标
            let maxX = that.map.offsetWidth / that.snake.width
            let maxY = that.map.offsetHeight / that.snake.height
            let headX = that.snake.body[0].x
            let headY = that.snake.body[0].y
            if (headX < 0 || headX >= maxX) {
                alert('Game over')
                clearInterval(time)
            }
            if (headY < 0 || headY >= maxY) {
                alert('Game over')
                clearInterval(time)
            }
        }, 150);
    }

    window.Game = Game
})()